package com.snail.common.tenant.interceptor;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.snail.common.core.constant.SecurityConstants;
import com.snail.common.core.utils.ServletUtils;
import com.snail.common.core.utils.StringUtils;
import com.snail.common.tenant.config.TenantProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 多租户拦截器
 * @Author: Snail
 * @CreateDate: 2023/8/3 15:23
 * @Version: V1.0
 */
public class TenantInterceptor implements AsyncHandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(TenantInterceptor.class);
    private final TenantProperties tenantProperties;

    public TenantInterceptor(TenantProperties tenantProperties) {
        this.tenantProperties = tenantProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ds = StringUtils.defaultIfEmpty(ServletUtils.getHeader(request, SecurityConstants.TENANT_ID), tenantProperties.getDefaultTenantVal());
        //数据源切换
        DynamicDataSourceContextHolder.push(ds);
        log.info("切换当前线程数据源：" + ds);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String ds = DynamicDataSourceContextHolder.peek();
        //清除当前数据源
        DynamicDataSourceContextHolder.clear();
        log.info("清空当前线程数据源：" + ds);
    }
}
